/**
 * 作者:hanbo
 * 日期:2018/12/2911:41
 * 描述:基于范围对要素进行查询
 */

define(["dojo/_base/declare", "esri/geometry/geometryEngine", "esri/Graphic"], function (declare, geometryEngine, Graphic) {
    return declare("ExtendQuery", null, {
        constructor: function (view) {
            this.view = view
        },
        queryExtend(layer, geometry) {
            var query = layer.createQuery();
            query.geometry = geometry;
            query.spatialRelationship = "intersects";
            layer.queryFeatures(query).then(this._showResult);
        },
        queryExtendFeature(layer, geometry) {
            var that = this;
            var query = layer.createQuery();
            query.geometry = geometry;
            query.spatialRelationship = "intersects";
            layer.queryFeatures(query).then(function (result) {
                that.showIntersect(result.features, geometry)
            });
        },
        showIntersect(features, buffer) {
            if (features.length == 0) {
                return
            }
            var geos = [];
            for (var i = 0; i < features.length; i++) {
                geos.push(features[i].geometry);
            }
            var results = geometryEngine.intersect(geos, buffer);
            for (var i = 0; i < features.length; i++) {
                features[i].geometry = results[i];
                features[i].attributes.MJ = Math.abs(geometryEngine.planarArea(results[i], "square-meters"));
            }
            this._showClipResult({
                features: features
            })
        },
        queryExtendArea(layer, geometry, per_cost) {
            var query = layer.createQuery();
            query.geometry = geometry;
            query.spatialRelationship = "intersects";
            layer.queryFeatures(query).then(function (results) {
                if (results.features.length == 0) {
                    return
                }
                var data = [];
                var area = 0;
                var allCost = 0;
                results.features.forEach(function (geometry) {
                    var attr = geometry.attributes;
                    area = area + attr.MJ;
                    attr.cost = (attr.MJ * Number(per_cost)).toFixed(2);
                    allCost = allCost + Number(attr.cost);
                    data.push(attr);
                });

                var tableData = {
                    "total": 3,
                    "rows": data,
                    "footer": [{
                        "id": "合计", "MJ": area, "cost": allCost
                    }]
                };

                $("#tableWindow").window({
                    onClose: function () {
                        //清除之前绘制
                        view.graphics.removeAll();
                        useExtend = null;
                        $('#costEstimate').linkbutton('disable');
                    }
                });
                $("#tableWindow").window("open");
                $("#queryTable").datagrid({
                    columns: [
                        [
                            {
                                field: "id",
                                title: "地块编号"
                            },
                            {
                                field: "cost",
                                title: "征地费用(元)"
                            },
                            {
                                field: "PEOPLE",
                                title: "权属人"
                            },
                            {
                                field: "DLMC",
                                title: "用地类型"
                            },
                            {
                                field: "MJ",
                                title: "面积（平方米）"
                            }
                        ]],    //动态取标题
                    data: tableData,
                    fitColumns: true,
                    showFooter: true,
                    singleSelect: true,
                    rownumbers: true,
                    onClickRow: function (index) {
                        view.goTo(results.features[index].geometry).then(function () {
                            view.popup.clear();
                            view.popup.open({
                                features: [results.features[index]]
                            })
                        });

                    }
                });

            });
        },
        querySQL(layer, sql) {
            var query = layer.createQuery();
            query.where = query.where + sql;
            layer.queryFeatures(query).then(this._showResult);
        },
        statics(layer, type,title) {
            var that = this;
            this.view.whenLayerView(layer).then(function (layerView) {
                var query = layerView.layer.createQuery();
                query.outStatistics = [{
                    onStatisticField: "MJ",
                    outStatisticFieldName: "MJ",
                    statisticType: "sum"
                }];
                if (type) {
                    query.groupByFieldsForStatistics = ["DLMC"];
                } else {
                    query.groupByFieldsForStatistics = ["QSDWMC"];
                }
                layerView.queryFeatures(query).then(
                    function (e) {
                        var data = [];
                        if (type) {
                            for (var i = 0; i < e.features.length; i++) {
                                data.push({
                                    name: e.features[i].attributes.DLMC,
                                    value: e.features[i].attributes.MJ.toFixed(2)
                                })
                            }
                        } else {
                            for (var i = 0; i < e.features.length; i++) {
                                data.push({
                                    name: e.features[i].attributes.QSDWMC,
                                    value: e.features[i].attributes.MJ.toFixed(2)
                                })
                            }
                        }
                        that._showStatics(data, title);
                    },
                    function (err) {
                        console.log(err)
                    }
                )
            });
        },
        staticsArea_people(layer, geometry, per_cost) {
            var that = this;
            this.view.whenLayerView(layer).then(function (layerView) {
                var query = layerView.layer.createQuery();
                query.outStatistics = [{
                    onStatisticField: "MJ",
                    outStatisticFieldName: "MJ",
                    statisticType: "sum"
                }, {
                    onStatisticField: "id",
                    outStatisticFieldName: "id",
                    statisticType: "count"
                }];
                query.geometry = geometry;
                query.spatialRelationship = "intersects";
                query.groupByFieldsForStatistics = ["PEOPLE"];
                layerView.queryFeatures(query).then(
                    function (results) {
                        if (results.features.length == 0) {
                            return
                        }
                        var data = [];
                        console.log(results.features);
                        results.features.forEach(function (geometry) {
                            var attr = geometry.attributes;
                            attr.cost = (attr.MJ * Number(per_cost)).toFixed(2);
                            data.push(attr);
                        });
                        $("#tableWindow").window({
                            onClose: function () {
                                //清除之前绘制
                                view.graphics.removeAll();
                                useExtend = null;
                                $('#costEstimate').linkbutton('disable');
                            }
                        });
                        $("#tableWindow").window("open");
                        $("#queryTable").datagrid({
                            columns: [
                                [
                                    {
                                        field: "id",
                                        title: "地块数量"
                                    },
                                    {
                                        field: "cost",
                                        title: "费用（元）"
                                    },
                                    {
                                        field: "MJ",
                                        title: "面积（平方米）"
                                    },
                                    {
                                        field: "PEOPLE",
                                        title: "所有人"
                                    }

                                ]],    //动态取标题
                            data: data,
                            fitColumns: true,
                            singleSelect: true
                        });

                    },
                    function (err) {
                        console.log(err)
                    }
                )
            });
        },
        _showCost_id() {
        },
        _showResult(results) {
            var view = this.view;
            if (results.features.length == 0) {
                return
            }
            var data = [];
            var area = 0;
            results.features.forEach(function (geometry) {
                var attr = geometry.attributes;
                area = area + geometry.attributes.MJ;
                data.push(attr);
            });
            var tableData = {
                // "total": results.features.length,
                "total": 3,
                "rows": data,
                "footer": [{
                    "PEOPLE": "合计", "MJ": area
                }]
            };
            $("#tableWindow").window({
                onClose: function () {
                    //清除之前绘制
                    view.graphics.removeAll();
                }
            });
            $("#tableWindow").window("open");

            $("#queryTable").datagrid({
                columns: [
                    [
                        {
                            field: "PEOPLE",
                            title: "权属人"
                        }, {
                        field: "DLMC",
                        title: "用地类型"
                    }, {
                        field: "DLBM",
                        title: "地类号"
                    }, {
                        field: "TBBH",
                        title: "图斑号"
                    },
                        {
                            field: "MJ",
                            title: "面积（平方米）"

                        },
                        {
                            field: "TIME",
                            title: "登记时间",
                            formatter: function (data) {
                                if (data) {
                                    return new Date(data).toLocaleString();
                                } else {
                                    return ""
                                }
                            }
                        },
                        {
                            field: "QSDWMC",
                            title: "所属村组"
                        }]],    //动态取标题
                data: tableData,
                fitColumns: true,
                singleSelect: true,
                showFooter: true,
                rownumbers: true,
                onClickRow: function (index) {
                    console.log(results.features[index].geometry);
                    view.goTo(results.features[index].geometry).then(function () {
                        view.popup.clear();
                        view.popup.open({
                            features: [results.features[index]]
                        })
                    });

                }
            });
        },
        _showClipResult(results) {
            var view = this.view;
            if (results.features.length == 0) {
                return
            }
            var data = [];
            var area = 0;
            results.features.forEach(function (geometry) {
                var attr = geometry.attributes;
                area = area + attr.MJ;
                data.push(attr);
            });

            var tableData = {
                // "total": results.features.length,
                "total": 3,
                "rows": data,
                "footer": [{
                    "PEOPLE": "合计", "MJ": area
                }]
            };
            $("#tableWindow").window({
                onClose: function () {
                    //清除之前绘制
                    view.graphics.removeAll();
                }
            });
            $("#tableWindow").window("open");

            $("#queryTable").datagrid({
                columns: [
                    [
                        {
                            field: "PEOPLE",
                            title: "权属人"
                        }, {
                        field: "DLMC",
                        title: "用地类型"
                    }, {
                        field: "DLBM",
                        title: "地类号"
                    }, {
                        field: "TBBH",
                        title: "图斑号"
                    },
                        {
                            field: "MJ",
                            title: "面积（平方米）"
                        },
                        {
                            field: "TIME",
                            title: "登记时间",
                            formatter: function (data) {
                                if (data) {
                                    return new Date(data).toLocaleString();
                                } else {
                                    return ""
                                }
                            }
                        },
                        {
                            field: "QSDWMC",
                            title: "所属村组"
                        }]],    //动态取标题
                data: tableData,
                fitColumns: true,
                showFooter: true,
                singleSelect: true,
                rownumbers: true,
                onClickRow: function (index) {
                    view.goTo(results.features[index].geometry).then(function () {
                        var polySym = {
                            type: "simple-fill", // autocasts as new SimpleFillSymbol()
                            color: [255, 0, 0, 0.1],
                            outline: {
                                color: [255, 0, 0, 1],
                                width: 2
                            }
                        };
                        //移除原有红色
                        for (var i = 0; i < view.graphics.items.length; i++) {
                            if (view.graphics.items[i].attributes && view.graphics.items[i].attributes.selectState) {
                                view.graphics.removeAt(i);
                                break;
                            }
                        }
                        //添加红色选中效果
                        view.graphics.add((new Graphic({
                            geometry: results.features[index].geometry,
                            symbol: polySym,
                            attributes: {selectState: true}
                        })));
                    });

                }
            });
        },
        queryExport(layer, geometry) {
            var query = layer.createQuery();
            query.geometry = geometry;
            query.spatialRelationship = "intersects";
            layer.queryFeatures(query).then(function (e) {

                this.view.graphics.removeAll();//清楚之前的绘制
                var result = {
                    features: e.features,
                    fields: e.fields,
                    spatialReference: e.spatialReference,
                    geometryType: e.geometryType
                };
                var blob = new Blob([JSON.stringify(result)], {type: "text/plain;charset=utf-8"});
                saveAs(blob, "导出.txt");
            });
        },
        queryChange(layer, geometry) {
            var query = layer.createQuery();
            query.geometry = geometry;
            query.spatialRelationship = "intersects";
            layer.queryFeatures(query).then(function (e) {
                $("#changeWindow").panel('open');
                this.view.graphics.removeAll();//清楚之前的绘制
                var result = {
                    features: e.features,
                    fields: e.fields,
                    spatialReference: e.spatialReference,
                    geometryType: e.geometryType
                };
                var data = {
                    "total": 5, "rows": [
                        {"name": "权属人姓名", "value": result.features[0].attributes.PEOPLE, "group": "变更前"},
                        {"name": "面积", "value": result.features[0].attributes.MJ, "group": "变更前"},
                        {"name": "所属村组", "value": result.features[0].attributes.QSDWMC, "group": "变更前"},
                        {"name": "权属人姓名", "value": "", "group": "变更后", "editor": "text"},
                        {"name": "所属村组", "value": "", "group": "变更后", "editor": "text"},
                        {
                            "name": "身份证",
                            "value": "",
                            "group": "申请材料",
                            "editor": {"type": "filebox", "options": {"buttonText": "选择文件"}}
                        },
                        {
                            "name": "登记申请书",
                            "value": "",
                            "group": "申请材料",
                            "editor": {"type": "filebox", "options": {"buttonText": "选择文件"}}
                        },
                        {
                            "name": "宅基地使用权证书",
                            "value": "",
                            "group": "申请材料",
                            "editor": {"type": "filebox", "options": {"buttonText": "选择文件"}}
                        },
                        {
                            "name": "其他证明材料",
                            "value": "",
                            "group": "申请材料",
                            "editor": {"type": "filebox", "options": {"buttonText": "选择文件", "multiple": true}}
                        }
                    ]
                };
                $('#changeInfo').propertygrid({
                    data: data,
                    showHeader: false,
                    showGroup: true
                });
            });
        },
        queryPrint(layer, geometry) {
            var query = layer.createQuery();
            query.geometry = geometry;
            query.spatialRelationship = "intersects";
            layer.queryFeatures(query).then(function (e) {

                view.graphics.removeAll();//清楚之前的绘制
                var result = {
                    features: e.features,
                    fields: e.fields,
                    spatialReference: e.spatialReference,
                    geometryType: e.geometryType
                };
                sessionStorage.setItem("data", JSON.stringify(result));
                window.open("certificate.html", "_blank");
            });
        },
        _showStatics(data, title) {
            $("#dialog_statics_result").dialog('open');
            $("#dialog_statics_result").dialog('setTitle', title);
            // 基于准备好的dom，初始化echarts实例

            document.getElementById("chart_frame").contentWindow.loadData(data);
        }
    })
});